package com.atguigu.gulimall.auth.web;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.feign.ThirdPartFeignService;
import com.atguigu.gulimall.auth.vo.UserLoginVo;
import com.atguigu.gulimall.auth.vo.UserRegistVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Author baiWT
 * @Description
 * @Date 2022/4/4 22:10
 **/
@Controller
public class loginController {

    @Resource
    private ThirdPartFeignService thirdPartFeignService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private MemberFeignService memberFeignService;

    @GetMapping("/login.html")
    public String loginPage(HttpSession session){
        Object sessionAttribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (sessionAttribute == null){
            return "login";
        }else {
            return "redirect:http://gulimall.com";
        }
    }

    @PostMapping("/register/login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session){
        //远程登录
        R r = memberFeignService.login(vo);

        if (r.getCode() == 0){
            MemberRespVo respVo = r.getData("data", MemberRespVo.class);
            session.setAttribute(AuthServerConstant.LOGIN_USER,respVo);
            return "redirect:http://gulimall.com";
        }else {
            Map<String,String> errMap = new HashMap<>();
            errMap.put("msg",r.getData("msg",String.class));
            redirectAttributes.addFlashAttribute("loginErrMsg",errMap);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }

    @ResponseBody
    @GetMapping("/register/send/code")
    public R sendCode(@RequestParam("phone") String phone){
        //TODO 1、接口防刷

        //redis缓存验证码防止60秒内再次发送
        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone);
        if (!StringUtils.isEmpty(redisCode)){
            long l = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - l < 60 * 1000){
                //60秒内不能再发
                return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(),BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
            }
        }

        //验证码的再次校验.redis  sms:code:15700501985 -> 45678
        String code = UUID.randomUUID().toString().substring(0,5)+"_"+System.currentTimeMillis();
        stringRedisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone,code,5, TimeUnit.MINUTES);

        thirdPartFeignService.sendCode(phone,code.substring(0,5));
        return R.ok();
    }

    @PostMapping("/register/register")
    public String regist(@Valid UserRegistVo vo, BindingResult result, RedirectAttributes redirectAttributes){
        if (result.hasErrors()){

//            result.getFieldErrors().stream().map((fieldError)->{
//                String field = fieldError.getField();
//                String defaultMessage = fieldError.getDefaultMessage();
            Map<String,String> errMap = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField,FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("regErrMsg",errMap);
            //model.addAttribute("errMap",errMap);
            //校验出错，转到注册页
            return "redirect:http://auth.gulimall.com/reg.html";
        }

        //真正注册,调用远程服务进行注册
        //1、校验验证码
        String code = vo.getCode();
        String s = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX+vo.getPhone());
        if (!StringUtils.isEmpty(s)){
            if (code.equals(s.split("_")[0])){
                //删除验证码,令牌机制
                stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX+vo.getPhone());
                //验证码通过,开始调用远程服务进行注册
                R r = memberFeignService.register(vo);
                if (r.getCode() == 0){
                    //成功
                    //注册成功回到首页，回到登录页

                    return "redirect:http://auth.gulimall.com/login.html";
                }else {
                    Map<String,String> errMap = new HashMap<>();
                    errMap.put("msg",r.getData("msg",String.class));
                    return "redirect:http://auth.gulimall.com/reg.html";
                }
            }else {
                Map<String,String> errMap = new HashMap<>();
                errMap.put("code","验证码错误");
                redirectAttributes.addFlashAttribute("errMap",errMap);
                //校验出错，转到注册页
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        }else {
            Map<String,String> errMap = new HashMap<>();
            errMap.put("code","验证码错误");
            redirectAttributes.addFlashAttribute("errMap",errMap);
            //校验出错，转到注册页
            return "redirect:http://auth.gulimall.com/reg.html";
        }
    }
}
